package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"shuqi-novel/cache"
	"shuqi-novel/model"
	"shuqi-novel/shuqirpc/internal/svc"
	"shuqi-novel/shuqirpc/shuqirpc"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListLogic {
	return &ListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListLogic) List(in *shuqirpc.ListRequest) (*shuqirpc.ListResponse, error) {
	// todo: add your logic here and delete this line
	off := (in.Page - 1) * in.Size
	var novel []model.Novel
	key := fmt.Sprintf("list%d%d%d", in.UserId, in.Page, in.Size)
	result, _ := cache.Rdb.Get(cache.Ctx, key).Result()
	if result == "" {
		model.DB.Where("user_id=?", in.UserId).Offset(int(off)).Limit(int(in.Size)).Find(&novel)
		marshal, _ := json.Marshal(novel)
		cache.Rdb.Set(cache.Ctx, key, marshal, time.Hour*1)
	} else {
		json.Unmarshal([]byte(result), &novel)
	}
	var listnovels []*shuqirpc.List
	for _, novels := range novel {
		list := shuqirpc.List{
			Title:   novels.Title,
			Image:   novels.Image,
			UserId:  int64(novels.UserId),
			NovelId: int64(novels.ID),
		}
		listnovels = append(listnovels, &list)
	}
	return &shuqirpc.ListResponse{
		List: listnovels,
	}, nil
}
